import React, { ReactNode } from 'react';
import { Form, Row, Col, Button } from 'antd';
import { connect } from 'dva';
import { StateType } from '@/common-typings';
import { mapStateToProps, ObjectType, getRangePickerTime } from '../../../utils';
import { riskMark } from '@/const/risk';
import { BaseInput, BaseRangePicker, BaseSelect, InquiryAreaButton } from '@/components';
import style from './form.less';

/**
 *  关于日期控件的规则：
 *  查询：
 *    可选日期最新值为当前自然日，可选日期区间为365日（起日不限制、结束未选择默认为当日）
 *  重置：
 *    发送请求的时间为当前自然日
 * */
class RiskInquiryForm extends React.PureComponent<StateType> {
  public state = {
    currentBatchOperation: '请选择',
    userRiskList: '', // 通过风险标签查询数据
  };

  public BatchOperationData = [
    {
      id: 1,
      text: '锁定',
    },
    {
      id: 2,
      text: '修改层级',
    },
  ];

  // 查询用户风险名单
  handleGetUserList = (condition: ObjectType) => {
    const {
      dispatch,
      risk: {
        tableData: { pageSize },
      },
    } = this.props;
    const { userRiskList } = this.state;
    dispatch({
      type: 'risk/getUserRiskDataEffect',
      payload: {
        ...condition,
        page: 1,
        size: pageSize,
        userRiskList,
      },
    });
  };

  // 点击表单区的查询
  handleSubmit = (e: ObjectType) => {
    e.preventDefault();
    this.props.form.validateFields((err: null | ObjectType, values: ObjectType) => {
      if (!err) {
        const rangeTime = getRangePickerTime(values);
        // 查询用户风险名单
        const condition = {
          username: values.username,
          startDate: rangeTime[0],
          endDate: rangeTime[1],
        };
        // 查询用户风险名单
        this.handleGetUserList(condition);

        // 保存查询条件 表格翻页的时候发请求使用
        this.props.dispatch({
          type: 'risk/setInquiryCondition',
          payload: {
            ...condition,
            userRiskList: this.state.userRiskList,
          },
        });
      }
    });
  };

  // 清空表单选项
  handleResetForm = () => {
    this.props.dispatch({
      type: 'risk/setPageSize',
      payload: {
        current: 1,
      },
    });

    this.setState({
      userRiskList: '',
    });

    const defaultInquiryCondition = {
      startDate: getRangePickerTime()[0],
      endDate: getRangePickerTime()[1],
      userRiskList: '',
    };
    this.handleGetUserList(defaultInquiryCondition);
  };

  // 导出
  downloadExcel = (e: ObjectType) => {
    e.preventDefault();
    const { form, dispatch } = this.props;
    form.validateFields((err: null | ObjectType, values: ObjectType) => {
      if (!err) {
        const rangeTime = getRangePickerTime(values);
        dispatch({
          type: 'risk/excelExportEffect',
          payload: {
            username: values.username,
            startDate: rangeTime[0],
            endDate: rangeTime[1],
            userRiskList: this.state.userRiskList,
          },
        });
      }
    });
  };

  // 显示标签变化
  handleRiskMarkDisplayChange = (value: string[]) => {
    const currentRiskList = this.modifyRiskMark(value);
    // 保存风险标签
    this.props.dispatch({
      type: 'risk/changeDisplayRiskMarkColumnDisplay',
      payload: currentRiskList,
    });
  };

  // 风险标签变化
  handleRiskMarkChange = (value: string[]) => {
    const riskList = this.modifyRiskMark(value);
    const userRisk = riskList.map((val: StateType) => val.id);
    const userRiskList = userRisk.join(',');
    this.setState({
      userRiskList,
    });
  };

  // 获取选中的风险标签的数据
  modifyRiskMark = (value: string[]) => {
    const riskList: ObjectType[] = [];
    riskMark.forEach((item: ObjectType) => {
      value.forEach((val: string) => {
        if (item.text === val) {
          riskList.push(item);
        }
      });
    });
    return riskList;
  };

  // 批量操作切换
  BatchOperationChange = (value: string) => {
    this.setState({
      currentBatchOperation: value,
    });
  };

  // 批量操作执行
  batchOperationHandle = () => {
    const {
      tableData: { selectedUserList },
    } = this.props.risk;
    const { currentBatchOperation } = this.state;
    if (currentBatchOperation === '锁定') {
      this.props.showLockModal();
    } else if (currentBatchOperation === '修改层级') {
      this.props.showModifyLevelModal();
    }

    const BatchOperationBtnDisabled =
      currentBatchOperation === '请选择' || selectedUserList.length === 0;

    this.props.toBatchOperation(!BatchOperationBtnDisabled);
  };

  public render(): ReactNode {
    const { getFieldDecorator } = this.props.form;
    const {
      formData: { displayMarks },
      tableData: { selectedUserList },
    } = this.props.risk;
    const { currentBatchOperation } = this.state;
    const mark: string[] = [];
    displayMarks.forEach((val: ObjectType) => {
      mark.push(val.text);
    });
    const BatchOperationBtnDisabled =
      currentBatchOperation === '请选择' || selectedUserList.length === 0;
    const displayMarkInitialValue = mark.length ? mark : [];
    return (
      <Form className={style.formWrapStyle} labelAlign="left" onSubmit={this.handleSubmit}>
        <Row gutter={30}>
          <Col span={5}>
            <BaseInput
              getFieldDecorator={getFieldDecorator}
              getFieldDecoratorId="username"
              label="账户名"
              labelCol={{ span: 7 }}
            />
          </Col>
          <Col span={8}>
            <BaseSelect<>
              label="风险标签"
              placeholder="请选择风险标签"
              getFieldDecorator={getFieldDecorator}
              id="risk-mark"
              optionsData={riskMark}
              OptionKeyAttr="id"
              OptionValueAttr="text"
              OptionTextAttr="text"
              mode="multiple"
              onChange={this.handleRiskMarkChange}
              maxTagTextLength={2} // 最大显示的 tag 文本长度
              maxTagCount={2} // 最多显示多少个 tag
              labelCol={{ span: 5 }}
            />
          </Col>
          <Col span={7}>
            <BaseRangePicker
              getFieldDecorator={getFieldDecorator}
              id="select-date"
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 4 }}
              className={style.riskFormRangePicker}
            />
          </Col>
          <Col span={4}>
            <InquiryAreaButton
              className={style.inquiryBtn}
              form={this.props.form}
              handleResetCallBack={this.handleResetForm}
            />
          </Col>
        </Row>
        <Row gutter={20}>
          <Col span={2}>
            <Button type="primary" onClick={this.downloadExcel}>
              导出
            </Button>
          </Col>
          <Col span={14}>
            <BaseSelect<>
              label="显示标签"
              placeholder="显示标签"
              getFieldDecorator={getFieldDecorator}
              id="select-display-mark"
              optionsData={riskMark}
              OptionKeyAttr="id"
              OptionValueAttr="text"
              OptionTextAttr="text"
              mode="multiple"
              onChange={this.handleRiskMarkDisplayChange}
              maxTagTextLength={8} // 最大显示的 tag 文本长度
              labelCol={{ span: 5 }}
              initialValue={displayMarkInitialValue}
            />
          </Col>
          <Col span={6}>
            <BaseSelect<>
              label="批量操作"
              getFieldDecorator={getFieldDecorator}
              id="batch-operation"
              optionsData={this.BatchOperationData}
              OptionKeyAttr="id"
              OptionValueAttr="text"
              OptionTextAttr="text"
              onChange={this.BatchOperationChange}
              labelCol={{ span: 7 }}
              wrapperCol={{ span: 3 }}
              initialValue={currentBatchOperation}
            />
          </Col>
          <Col span={2}>
            <Button
              type="dashed"
              className={BatchOperationBtnDisabled ? '' : style.BatchOperationBtn}
              disabled={BatchOperationBtnDisabled}
              onClick={this.batchOperationHandle}
            >
              执行
            </Button>
          </Col>
        </Row>
      </Form>
    );
  }
}

export default connect(mapStateToProps)(Form.create()(RiskInquiryForm));
